package com.room.core.annotation.support;

import com.room.core.annotation.LoginUser;
import com.room.core.dto.UserInfo;
import com.room.core.exception.NotLoginException;
import com.room.core.util.CoreConstant;
import com.room.core.util.JWTUtil;
import com.room.core.util.StringUtil;
import com.room.core.util.UserTokenManage;
import org.springframework.core.MethodParameter;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

public class LoginUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

	/**
	 * 判断方法是否需要用户参数
	 * @param parameter
	 * @return
	 */
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterType().isAssignableFrom(UserInfo.class)
				&& parameter.hasParameterAnnotation(LoginUser.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer container,
                                  NativeWebRequest request,
                                  WebDataBinderFactory factory) throws Exception {

		String token = request.getHeader(CoreConstant.TOKEN_KEY);
		if (StringUtil.isEmpty(token)) {
			throw new NotLoginException();
		}

		//从缓存中拿出token,可以reids或系统map实现
		UserInfo userInfo = UserTokenManage.getUserInfo(token);
		if (userInfo == null){
			throw new NotLoginException();
		}
		return userInfo;
	}
}
